import axios from "axios";
import {ElLoading, ElMessageBox, ElNotification} from 'element-plus'
import {useAppStore} from "@/store/app.js";
import router from "@/router/index.js";

const axiosRequest = axios.create()

const loading = ref()
let reqList = []
let reqCount = 0

const addReq = (url, cancel) => {
    for (let i = 0; i < reqList.length; i++) {
        if (reqList[i] === url) {
            cancel()
            return
        }
    }
    reqList.push(url)
}

const resetReqList = (url) => {
    setTimeout(() => {
        for (let i = 0; i < reqList.length; i++) {
            if (reqList[i] === url) {
                reqList.splice(i, 1)
                break
            }
        }
    }, 1000)
}

axiosRequest.interceptors.request.use((config) => {
    reqCount++
    let cancel
    config.cancelToken = new axios.CancelToken(function (c) {
        cancel = c
    })
    addReq(`${config.method}:${config.url}`, cancel)
    if (config['bfLoading'] !== false) {
        loading.value = ElLoading.service({
            lock: true, text: 'Loading...',
        })
    }
    if ('get'.includes(config.method?.toLowerCase())) config.params = config.data
    const {token} = useAppStore()
    config.headers['authorize-token'] = token
    return config
}, (err) => {
    console.log('request err', err)
    reqCount--
    if (err?.config?.url) {
        resetReqList(`${err.config.method}:${err.config.url}`)
    }
    reqCount === 0 ? loading.value?.close() : true
    return Promise.reject(err)
})

axiosRequest.interceptors.response.use((res) => {
    reqCount--
    let response
    if (res.status === 200) {
        const {code, data} = res.data
        if (code === 20200) {
            response = data
        } else if (code === 20504) {
            ElMessageBox.confirm('请重新登录', {
                confirmButtonText: '重新登录',
                closeOnClickModal: false,
                showCancelButton: false,
                showClose: false,
                type: 'warning'
            }).then(() => {
                const appStore = useAppStore();
                appStore.clear()
                router.push({path: '/login'})
            })
        }
    }
    resetReqList(`${res.config.method}:${res.config.url}`)
    reqCount === 0 ? loading.value?.close() : true
    if (response === undefined) {
        response = Promise.reject(res)
        ElNotification({
            title: '错误', message: res?.data?.msg || res?.message || 'response err', type: 'error',
        })
    }
    return response
}, function (err) {
    console.log('response err', err)
    reqCount--
    if (err?.config?.url) {
        resetReqList(`${err.config.method}:${err.config.url}`)
    }
    if (!axios.isCancel(err)) {
        ElNotification({
            title: '错误', message: err?.message || 'response1 err', type: 'error',
        })
    }
    reqCount === 0 ? loading.value?.close() : true
    return Promise.reject(err)
})

export default function request(params) {
    return axiosRequest({
        headers: {"Content-Type": "application/json;charset=utf-8"}, timeout: 60000, ...params,
    })
}